package com.acane.instagram.feature.notification

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.design.theme.InstagramDarkGray
import com.acane.instagram.core.design.theme.Spacer
import com.acane.instagram.core.extension.clickableNoRipple
import com.acane.instagram.core.model.Notification
import com.acane.instagram.core.model.NotifyType.CHAT_MESSAGE
import com.acane.instagram.core.model.NotifyType.COMMENT_LIKE
import com.acane.instagram.core.model.NotifyType.FOLLOW_USER
import com.acane.instagram.core.model.NotifyType.POST_COMMENT
import com.acane.instagram.core.model.NotifyType.POST_LIKE
import com.acane.instagram.core.model.PostInfo
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.core.model.dto.CommentDTO
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import com.acane.instagram.feature.common.SessionManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@Composable
fun NotificationRoute(
    navController: NavHostController,
    toProfile: (String) -> Unit,
    toPostDetail: (String, String?) -> Unit,
) {
    NotificationScreen(
        navController = navController,
        toProfile = toProfile,
        toPostDetail = toPostDetail,
    )
}

@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NotificationScreen(
    navController: NavHostController,
    toProfile: (String) -> Unit,
    notificationViewModel: NotificationViewModel = viewModel(),
    toPostDetail: (String, String?) -> Unit,
) {

    val notificationDatum = notificationViewModel.notificationDatum.collectAsState()
    Scaffold(
        topBar = {
            TopAppBar(
                navigationIcon = {
                    IconButton(onClick = {
                        navController.popBackStack()
                    }) {
                        Image(
                            painter = painterResource(id = R.drawable.arrow_left),
                            contentDescription = "返回",
                            modifier = Modifier.size(24.dp),
                            contentScale = ContentScale.Fit
                        )
                    }
                },
                title = {
                    Text("通知", fontWeight = FontWeight.Bold)
                },
                actions = {

                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.White
                ),
            )
        },
        contentWindowInsets = WindowInsets(0.dp), // 移除默认内边距
        containerColor = Color.White,
        contentColor = Color.Black,
        content = { padding ->
            val coroutineScope = rememberCoroutineScope()

            Box (
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding)
            ) {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxSize(),
                    //contentPadding = PaddingValues(vertical = 8.dp, horizontal = 8.dp), // 设置顶部、底部和左右的间距
                ) {
                    notificationDatum.value.forEach { notification ->
                        when (notification.type) {
                            CHAT_MESSAGE -> {
                                return@forEach
                            }
                            POST_LIKE -> {
                                val postLikeNotification = notification as Notification.LikeNotification
                                if (postLikeNotification.likerId == SessionManager.currentUser?.id) {
                                    return@forEach
                                }
                                item {
                                    NotificationItem(
                                        notification = notification,
                                        toProfile = toProfile,
                                        scope = coroutineScope,
                                        toPostDetail = toPostDetail,
                                    )
                                }
                            }
                            POST_COMMENT -> {
                                val postCommentNotification = notification as Notification.CommentNotification
                                if (postCommentNotification.commenterId == SessionManager.currentUser?.id) {
                                    return@forEach
                                }
                                item {
                                    NotificationItem(
                                        notification = notification,
                                        toProfile = toProfile,
                                        scope = coroutineScope,
                                        toPostDetail = toPostDetail,
                                    )
                                }

                            }
                            COMMENT_LIKE -> {
                                val commentLikeNotification = notification as Notification.CommentLikeNotification
                                if (commentLikeNotification.likerId == SessionManager.currentUser?.id) {
                                    return@forEach
                                }
                                item {
                                    NotificationItem(
                                        notification = notification,
                                        toProfile = toProfile,
                                        scope = coroutineScope,
                                        toPostDetail = toPostDetail,
                                    )
                                }

                            }
                            FOLLOW_USER -> {
                                item {
                                    NotificationItem(
                                        notification = notification,
                                        toProfile = toProfile,
                                        scope = coroutineScope,
                                        toPostDetail = toPostDetail,
                                    )
                                }
                            }
                        }
                    }
                }
            }

        }
    )
}

@SuppressLint("CoroutineCreationDuringComposition", "UnrememberedMutableState")
@Composable
fun NotificationItem(
    scope: CoroutineScope,
    notification: Notification,
    toProfile: (String) -> Unit,
    toPostDetail: (String, String?) -> Unit,
    ) {
    Row (
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp) // 添加统一的上下间距
            .padding(end = 8.dp)
    ) {
        when (notification.type) {
            // 聊天消息不做处理
            CHAT_MESSAGE -> {
                return
            }

            POST_LIKE -> {
                val likeNotification = notification as Notification.LikeNotification
                val (liker, setLiker) = remember { mutableStateOf<UserInfo?>(null) }
                val (post, setPost) = remember { mutableStateOf<PostInfo?>(null) }
                scope.launch {
                    val likeResult = MyRetrofitDatasource.getUserById(likeNotification.likerId).data!!
                    val postResult = MyRetrofitDatasource.getPostById(likeNotification.postId).data!!
                    setLiker(likeResult)
                    setPost(postResult)
                }
                if (liker?.id == SessionManager.currentUser?.id) {
                    return
                }
                Row (
                    modifier = Modifier
                        .padding(start = 8.dp)
                        .clickable {
                            post?.id?.let { toPostDetail(it, null) }
                        },
                ) {
                    // 关注者头像
                    AsyncImage(
                        model = liker?.avatar?.let {
                            val url = "${Config.ADDRESS}avatars/$it"
                            Log.d("NotificationRoute", "🟢 尝试加载头像 URL: $url")
                            url
                        }?: run {
                            Log.d("NotificationRoute", "🔴 无服务器头像文件名，显示默认头像")
                            R.drawable.ic_default_avatar
                        },
                        contentDescription = "发布者头像",
                        modifier = Modifier
                            .size(50.dp)
                            .clip(CircleShape)
                            .background(Color.Transparent)
                            .clickableNoRipple {
                                liker?.id?.let { toProfile(it) }
                            },
                        contentScale = ContentScale.Crop,
                        error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                    )
                    androidx.compose.foundation.layout.Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = buildAnnotatedString {
                            // 用户名部分加粗
                            withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
                                append(liker?.userName ?: "未知用户")
                            }
                            // 后续文本正常
                            append(" 赞了你的帖子。")
                        },
                        fontSize = 14.sp,
                        modifier = Modifier
                            .weight(1f)
                    )
                    // 帖子封面
                    AsyncImage(
                        model = post?.thumbnailUrl.let {
                            val url = "${Config.ADDRESS}avatars/$it"
                            Log.d("NotificationRoute", "🟢 尝试加载帖子封面 URL: $url")
                            url
                        },
                        contentDescription = "帖子封面",
                        modifier = Modifier
                            .size(50.dp)
                            .clickable { }
                            .clip(RoundedCornerShape(10.dp)),
                        contentScale = ContentScale.Crop,
                        error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                    )
                }
            }

            POST_COMMENT -> {
                val commentNotification = notification as Notification.CommentNotification
                val (commenter, setCommenter) = remember { mutableStateOf<UserInfo?>(null) }
                val (isGetCommenter, setIsGetCommenter) = remember { mutableStateOf(false) }
                val (post, setPost) = remember { mutableStateOf<PostInfo?>(null) }
                scope.launch {
                    val commentResult = MyRetrofitDatasource.getUserById(commentNotification.commenterId).data!!
                    val postResult = MyRetrofitDatasource.getPostById(commentNotification.postId).data!!
                    setPost(postResult)
                    setCommenter(commentResult)
                    Log.d("NotificationRoute", "🟢 获取评论者信息成功: $commenter")
                    setIsGetCommenter(true)
                }
                if (notification.commenterId == SessionManager.currentUser?.id) {
                    return
                }
                if (isGetCommenter) {
                    Row (
                        modifier = Modifier
                            //.fillMaxWidth()
                            .padding(start = 8.dp)
                            .clickable {
                                post?.id?.let { toPostDetail(it, commentNotification.id) }
                            },
                    ) {
                        //发布者头像
                        AsyncImage(
                            model = commenter?.avatar?.let {
                                val url = "${Config.ADDRESS}avatars/$it"
                                Log.d("NotificationRoute", "🟢 尝试加载头像 URL: $url")
                                url
                            }?: run {
                                Log.d("NotificationRoute", "🔴 无服务器头像文件名，显示默认头像")
                                R.drawable.ic_default_avatar
                            },
                            contentDescription = "发布者头像",
                            modifier = Modifier
                                .size(50.dp)
                                .clip(CircleShape)
                                .background(Color.Transparent)
                                .clickableNoRipple {
                                    commenter?.id?.let { toProfile(it) }
                                },
                            contentScale = ContentScale.Crop,
                            error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                        )
                        androidx.compose.foundation.layout.Spacer(modifier = Modifier.width(8.dp))
                        Column(
                            verticalArrangement = Arrangement.Center,
                            modifier = Modifier
                                .weight(1f)  // 关键：分配剩余空间
                                .padding(end = 8.dp) // 与右侧图片保持间距
                        ) {
                            Text(
                                text = buildAnnotatedString {
                                    // 用户名部分加粗
                                    withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
                                        append(commenter?.userName ?: "未知用户")
                                    }
                                    // 后续文本正常
                                    append(" 评论了: ${commentNotification.content}")
                                },
                                fontSize = 14.sp,
                                modifier = Modifier
                                    .padding(end = 5.dp)
                            )
                            Row(
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Image(
                                    painter = painterResource(id = R.drawable.heart),
                                    contentDescription = null,
                                    modifier = Modifier
                                        .size(16.dp)
                                )
                                Spacer()
                                Text(
                                    text = "回复",
                                    color = InstagramDarkGray,
                                    fontSize = 12.sp
                                )
                            }
                        }
                        // 帖子封面
                        AsyncImage(
                            model = post?.thumbnailUrl.let {
                                val url = "${Config.ADDRESS}avatars/$it"
                                Log.d("NotificationRoute", "🟢 尝试加载帖子封面 URL: $url")
                                url
                            },
                            contentDescription = "帖子封面",
                            modifier = Modifier
                                .size(50.dp)
                                .clickable { }
                                .clip(RoundedCornerShape(10.dp)),
                            contentScale = ContentScale.Crop,
                            error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                        )
                    }

                }

            }

            COMMENT_LIKE -> {
                Log.d( "NotificationRoute", "🟢 --------------------这是评论点赞通知:\n$notification")
                val commentLikeNotification = notification as Notification.CommentLikeNotification
                val (liker, setLiker) = remember { mutableStateOf<UserInfo?>(null) }
                val (comment, setComment) = remember { mutableStateOf<CommentDTO?>(null) }
                val (post, setPost) = remember { mutableStateOf<PostInfo?>(null) }
                scope.launch {
                    val likeResult = MyRetrofitDatasource.getUserById(commentLikeNotification.likerId).data!!
                    val commentResult = MyRetrofitDatasource.getCommentById(commentLikeNotification.commentId).data!!
                    val postResult = MyRetrofitDatasource.getPostById(commentResult.postId).data!!
                    setLiker(likeResult)
                    setComment(commentResult)
                    setPost(postResult)
                    // 测试三种结果
                    Log.d( "NotificationRoute", "🟢 评论点赞通知：\n${commentLikeNotification}\n点赞者：${liker}\n评论：${comment}\n帖子：${post}")
                }
                if (liker?.id == SessionManager.currentUser?.id) {
                    return
                }
                Row (
                    modifier = Modifier
                        //.fillMaxWidth()
                        .padding(start = 8.dp)
                        .clickable {
                            Log.d(
                                "NotificationRoute",
                                "🟢 点击了评论点赞通知：帖子ID：${post?.id}====评论ID：${comment?.id}"
                            )
                            post?.id?.let { toPostDetail(it, comment?.id) }
                        },
                ) {
                    // 关注者头像
                    AsyncImage(
                        model = liker?.avatar?.let {
                            val url = "${Config.ADDRESS}avatars/$it"
                            Log.d("NotificationRoute", "🟢 尝试加载头像 URL: $url")
                            url
                        }?: run {
                            Log.d("NotificationRoute", "🔴 无服务器头像文件名，显示默认头像")
                            R.drawable.ic_default_avatar
                        },
                        contentDescription = "发布者头像",
                        modifier = Modifier
                            .size(50.dp)
                            .clip(CircleShape)
                            .background(Color.Transparent)
                            .clickableNoRipple {
                                liker?.id?.let { toProfile(it) }
                            },
                        contentScale = ContentScale.Crop,
                        error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                    )
                    androidx.compose.foundation.layout.Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = buildAnnotatedString {
                            // 用户名部分加粗
                            withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
                                append(liker?.userName ?: "未知用户")
                            }
                            // 后续文本正常
                            append(" 赞了你的评论:${comment?.content}")
                        },
                        fontSize = 14.sp,
                        modifier = Modifier
                            .weight(1f)
                    )
                    // 帖子封面
                    AsyncImage(
                        model = post?.thumbnailUrl.let {
                            val url = "${Config.ADDRESS}avatars/$it"
                            Log.d("NotificationRoute", "🟢 尝试加载帖子封面 URL: $url")
                            url
                        },
                        contentDescription = "帖子封面",
                        modifier = Modifier
                            .size(50.dp)
                            .clickable { }
                            .clip(RoundedCornerShape(10.dp)),
                        contentScale = ContentScale.Crop,
                        error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                    )
                }
            }

            FOLLOW_USER -> {
                val followNotification = notification as Notification.FollowNotification
                val (follower, setFollower) = remember { mutableStateOf<UserInfo?>(null) }
                scope.launch {
                    val followResult = MyRetrofitDatasource.getUserById(followNotification.followerId).data!!
                    setFollower(followResult)
                }
                Row (
                    modifier = Modifier
                        //.fillMaxWidth()
                        .padding(start = 8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 关注者头像
                    AsyncImage(
                        model = follower?.avatar?.let {
                            val url = "${Config.ADDRESS}avatars/$it"
                            Log.d("NotificationRoute", "🟢 尝试加载头像 URL: $url")
                            url
                        }?: run {
                            Log.d("NotificationRoute", "🔴 无服务器头像文件名，显示默认头像")
                            R.drawable.ic_default_avatar
                        },
                        contentDescription = "发布者头像",
                        modifier = Modifier
                            .size(50.dp)
                            .clip(CircleShape)
                            .background(Color.Transparent)
                            .clickableNoRipple {
                                follower?.id?.let { toProfile(it) }
                            },
                        contentScale = ContentScale.Crop,
                        error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                    )
                    androidx.compose.foundation.layout.Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = buildAnnotatedString {
                            // 用户名部分加粗
                            withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
                                append(follower?.userName ?: "未知用户")
                            }
                            // 后续文本正常
                            append(" 开始关注你了。")
                        },
                        fontSize = 14.sp,
                        modifier = Modifier
                            .weight(1f)
                    )
                    Column (
                        horizontalAlignment = Alignment.CenterHorizontally,
                    ){
                        Button(
                            onClick = { },
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color(0xFF1E90FF),
                                contentColor = Color.White
                            ),
                            shape = RoundedCornerShape(10.dp),
                            modifier = Modifier
                                .width(100.dp)
                            //.padding(end = 8.dp)
                        ) {
                            Text(
                                text = "关注",
                                fontSize = 14.sp,
                            )
                        }
                    }
                }
            }
        }
    }
}
